/*
 * File name: Plugin.java
 * 
 * Description: TODO
 *
 * Author: Theobald_wu, contact with wuqizhi@tydtech.com
 * 
 * Date: Mar 13, 2015  11:39:36 AM
 * 
 * Copyright (C) 2015 Zhouyou Network Technology Co.,Ltd.
 * 
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.freeme.pluginmanager;

import java.lang.reflect.Constructor;
import dalvik.system.PathClassLoader;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.util.Log;

public class Plugin {
    private static final String TAG = "[FREEME_DBG]Plugin";
    private Context mHostContext;
    private ActivityInfo mActivityInfo;
    private String mName; // the name of plugin
    private String mPackageName;
    private String mType;
    private BasePlugin mInstance;

    public Plugin(Context hostContext, String pkgName, ActivityInfo info) {
        mHostContext = hostContext;
        mActivityInfo = info;
        mPackageName = pkgName;
        initialize();
    }

    public final BasePlugin getInstance() {
        return mInstance;
    }

    public final String getType() {
        return mType;
    }

    public final String getName() {
        return mName;
    }

    public final String getPackageName() {
        return mPackageName;
    }

    private void initialize() {
        Bundle metaDatas = mActivityInfo.metaData;
        if (metaDatas != null) {
            mType = metaDatas.getString(PluginUtil.KEY_PLUGIN_TYPE);
        }

        // create the instance of plugin
        createPluginObject();

        if (mInstance != null) {
            mName = mInstance.mContext.getResources().getString(mActivityInfo.labelRes);
            Log.i(TAG, "initialize(): plugin name = " + mName);
        }
    }

    private void createPluginObject() {
        Log.i(TAG, "createPluginObject(): Enter ");
        ClassLoader cl = new PathClassLoader(mActivityInfo.applicationInfo.sourceDir,
                mHostContext.getClassLoader());
        try {
            Constructor constructor = cl.loadClass(mActivityInfo.name).getConstructor(
                    Context.class, String.class);
            mInstance = (BasePlugin) constructor.newInstance(mHostContext, mPackageName);
        } catch (Exception e) {
            Log.i(TAG, "createPluginObject(): error! " + e.getMessage());
            e.printStackTrace();
        }
    }

    // TODO: can configure plugin properties
}
